//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.WindowsPhoneChat.Commands
{
    using System;
    using System.Net;
    using System.Windows;
    using Microsoft.Samples.ServiceBus;
    using Microsoft.Samples.ServiceBus.Messaging;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.Controllers;
    using Microsoft.Samples.ServiceBus.WindowsPhoneChat.ViewModels;

    public class AddTopicCommand : DialogCommand<MainPageViewModel>
    {
        protected override bool CanExecute(MainPageViewModel viewModel)
        {
            return viewModel != null;
        }

        protected override void Execute(MainPageViewModel viewModel)
        {
            var dialogViewModel = new AddTopicDialogViewModel();

            viewModel.ShowDialog("AddTopic", dialogViewModel, this.OnDialogClosed, viewModel);
        }

        protected override void OnDialogClosed(bool cancelled, ViewModel viewModel, object state)
        {
            var mainWindowViewModel = (MainPageViewModel)state;
            var dialogViewModel = (AddTopicDialogViewModel)viewModel;

            if (!cancelled)
            {
                var newTopicName = Uri.EscapeDataString(dialogViewModel.Name);
                var asyncState = new AsyncState { MainPageViewModel = mainWindowViewModel, DialogViewModel = dialogViewModel };

                // Asynchronously begin creating a new topic with the Silverlight API
                TopicClient.BeginCreateTopic(newTopicName, App.Context.TokenProvider, this.OnTopicCreated, asyncState);
            }

            mainWindowViewModel.State = "Chat";
        }

        private void OnTopicCreated(IAsyncResult result)
        {
            // When the request to create the topic has completed, end the Async call
            var asyncState = (AsyncState)result.AsyncState;
            TopicClient topicClient = null;
            HttpWebException exception = null;

            try
            {
                topicClient = TopicClient.EndCreateTopic(result);
            }
            catch (HttpWebException e)
            {
                exception = e;
            }

            // Update the UI with the result of the 'Add Topic' command
            ViewController.Current.BeginInvokeUI(() =>
            {
                if (topicClient != null)
                {
                    // Add the new topic to the topics list
                    var topicViewModel = asyncState.MainPageViewModel.ChatTopicListControlViewModel.AddTopic(topicClient, false);

                    if (asyncState.DialogViewModel.ShouldSubscribe)
                    {
                        Commands.SubscribeToTopic.Execute(topicViewModel);
                    }
                }
                else
                {
                    if (exception != null)
                    {
                        // A HTTP 409 error indicates that the Topic already exists, so cannot be 
                        // created
                        if (exception.StatusCode == HttpStatusCode.Conflict)
                        {
                            MessageBox.Show("Cannot create the new topic, because a topic with that name already exists.");
                        }
                    }
                }
            });
        }

        private struct AsyncState
        {
            public MainPageViewModel MainPageViewModel;

            public AddTopicDialogViewModel DialogViewModel;
        }
    }
}
